//
//  RecommendViewController.m
//  Fangmm
//
//  Created by 阮琦 on 16/3/21.
//  Copyright © 2016年 com.fangmm. All rights reserved.
//

#import "RecommendViewController.h"
#import "UserHomepageViewController.h"
#import "HouseDetailViewController.h"

#import "RecommendChiefTableViewCell.h"
#import "RecommendHouseTableViewCell.h"

#import "EmptyView.h"

#import "ACMacros.h"
#import "Utility.h"
#import "Constants.h"
#import "HttpServer.h"
#import "Recommend.h"
#import "MJRefresh.h"

#import <SDWebImage/UIImageView+WebCache.h>
#import <MobClick.h>

@interface RecommendViewController () <UITableViewDataSource, UITableViewDelegate>

@end

@implementation RecommendViewController {
    EmptyView *emptyView;
    
    NSMutableArray *recommends;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadRecommendData];
    [self configureNavigationBar];
    [self configureTableView];
    [self configureEmptyView];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated {
    recommends = [Utility getObjectForKey:kRecommendArray];
    if (self.tableView) {
        [self loadRecommendData];
    }
    [MobClick beginLogPageView:@"推荐页"];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - Configuring the view’s layout behavior
- (void)configureNavigationBar {
    self.title = @"推荐中心";
    self.navigationItem.hidesBackButton = true;
    UIImage *backImage = [[UIImage imageNamed:@"back-18-36"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc]initWithImage:backImage style:UIBarButtonItemStyleDone target:self action:@selector(clickToPopCancel)];
    self.navigationItem.leftBarButtonItem = leftBarButton;
}

- (void)configureTableView {
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Height - 64)];
    [self.view addSubview:self.tableView];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.tableView setDelegate:self];
    [self.tableView setDataSource:self];
    [self.tableView setBackgroundColor:RGBACOLOR(240, 240, 240, 1)];
    [self.tableView registerNib:[UINib nibWithNibName:@"RecommendChiefTableViewCell" bundle:nil] forCellReuseIdentifier:@"RecommendChiefTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"RecommendHouseTableViewCell" bundle:nil] forCellReuseIdentifier:@"RecommendHouseTableViewCell"];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
}

- (void)configureEmptyView {
    emptyView = [[EmptyView alloc]init];
    emptyView = [[[NSBundle mainBundle]loadNibNamed:@"EmptyView" owner:nil options:nil] lastObject];
    [emptyView setFrame:CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Height - 64)];
    [emptyView.emptyImage setImage:[UIImage imageNamed:@"OX_push-150-156"]];
    [emptyView.titleLabel setText:@"暂无推荐信息"];
}

#pragma mark - Triggering Methods
- (void)clickToPopCancel {
    [self.navigationController popToRootViewControllerAnimated:true];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (recommends.count == 0) {
        [self.tableView addSubview:emptyView];
        [emptyView setHidden:false];
    } else {
        [emptyView setHidden:true];
    }
    return recommends.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    Recommend *recommend = [[Recommend alloc]initWithDic:recommends[indexPath.row]];
    if ([recommend.recommendType isEqual:@"house"]) {
        RecommendHouseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RecommendHouseTableViewCell"];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *createDate =  [dateFormatter dateFromString:recommend.createTime];
        NSString *createTime = [dateFormatter stringFromDate:createDate];
        [cell.dateLabel setText:createTime];
        [cell.dateLabel setText:recommend.createTime];
        [cell.houseImage sd_setImageWithURL:[NSURL URLWithString:recommend.cover]];
        [cell.houseTitle setText:recommend.community];
        [cell.housePrice setText:[NSString stringWithFormat:@"%d",recommend.singleRentFloor]];
        [cell.houseRemarkLabel setText:[NSString stringWithFormat:@"%@ | %d室%d厅%d卫 | %dm²",recommend.community, recommend.roomNum, recommend.hallNum, recommend.toiletNum,recommend.area]];
        if (recommend.check) {
            [cell.checkLabel setHidden:true];
            [cell.checkImage setHidden:true];
            [cell.checkLabel setText:@"房妈妈验房保障"];
        } else {
            [cell.checkLabel setHidden:false];
            [cell.checkImage setHidden:false];
        }
        [cell.cheifNumLabel setText:[NSString stringWithFormat:@"已有%d位室长正在招募",recommend.teamNum]];
        [cell.recommendReasonLabel setText:[NSString stringWithFormat:@"推荐理由:%@",recommend.reason]];
        return cell;
    } else if ([recommend.recommendType isEqual:@"leader"]) {
        RecommendChiefTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RecommendChiefTableViewCell"];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *createDate =  [dateFormatter dateFromString:recommend.createTime];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        NSString *createTime = [dateFormatter stringFromDate:createDate];
        [cell.timeLabel setText:createTime];
        [cell.headerImage sd_setImageWithURL:[NSURL URLWithString:recommend.avatar]];
        if ([recommend.name isEqual:@""] || recommend.name == nil) {
            recommend.name = @"未完善";
        }
        [cell.chiefNameLabel setText:recommend.name];
        if (recommend.certification) {
            [cell.checkImage setImage:[UIImage imageNamed:@"check_ID-44-36"]];
        } else {
            [cell.checkImage setImage:[UIImage imageNamed:@"check_ID-44-36"]];
        }
        if (recommend.ageGroup == 0) {
            recommend.ageGroup = 90;
        }
        if ([recommend.constellation isEqual:@""] || recommend.constellation == nil) {
            recommend.constellation = @"未完善";
        }
        [cell.yearsOldLabel setText:[NSString stringWithFormat:@"%d后 %@",recommend.ageGroup, recommend.constellation]];
        if ([recommend.industry isEqual:@""] || recommend.constellation == nil) {
            recommend.industry = @"未完善";
        }
        if ([recommend.proffesion isEqual:@""] || recommend.proffesion == nil) {
            recommend.proffesion = @"未完善";
        }
        [cell.jobLabel setText:[NSString stringWithFormat:@"%@ - %@",recommend.industry, recommend.proffesion]];
        for (int i = 0; i < cell.tagsLabels.count; i++) {
            if (cell.tagsLabels.count <= recommend.tags.count) {
                UILabel *label = cell.tagsLabels[i];
                [label setText:recommend.tags[i]];
            }
        }
        
        [cell.chiefHouseCountLabel setText:[NSString stringWithFormat:@"室长房源:%d套",recommend.teamNum]];
        [cell.RecommendReasonLabel setText:[NSString stringWithFormat:@"推荐理由:%@",recommend.reason]];
        return cell;
    } else {
        UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        return cell;
    }
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 256;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    Recommend *recommend = [[Recommend alloc]initWithDic:recommends[indexPath.row]];
    if ([recommend.recommendType isEqual:@"leader"]) {
        UserHomepageViewController *userHomePageVC = [[UserHomepageViewController alloc] init];
        userHomePageVC.userId = recommend.userId;
        userHomePageVC.userName = recommend.name;
        [self.navigationController pushViewController:userHomePageVC animated:true];
    } else if ([recommend.recommendType isEqual:@"house"]) {
        HouseDetailViewController *houseDetailVC = [[HouseDetailViewController alloc] init];
        houseDetailVC.houseId = recommend.houseId;
        [self.navigationController pushViewController:houseDetailVC animated:true];
    }
}

- (void)loadRecommendData {
    [HttpServer getRecommendWithSuccessBlock:^(NSDictionary *successDic) {
        recommends = [successDic objectForKey:@"recommends"];
        [self.tableView reloadData];
    } withFailedBlock:^(id failData) {
        NSLog(@"%@",failData);
    }];
}

- (void)refreshData {
    [self loadRecommendData];
}

@end
